package com.aischool.interceptor;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;

import com.aischool.service.AiOrgService;
import com.aischool.service.AiParentService;
import com.aischool.utils.SysAppEnum;
import com.aischool.utils.UserAgentUtil;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;

public class FamilyInterceptor implements Interceptor {
	
	@Inject
	AiParentService aiParentService;
	@Inject
	AiOrgService aiOrgService;

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
				
		if (!checkParent(controller)) {
			return;
		}
		
		inv.invoke();
	}
	
	private boolean checkParent(Controller controller) {
		
		boolean is_pass = true;
		
		HttpServletRequest request = controller.getRequest();
        //HttpServletResponse response = controller.getResponse();
        
        String surl = request.getRequestURI().toString();
        String contextPath = request.getContextPath();
        surl = surl.substring(contextPath.length());
        
                
        if(StrKit.isBlank(surl) 
                || surl.startsWith("/front/family/login")
                || surl.startsWith("/front/family/register")
        ){
            return true;
        }
        
        int login_user_id = controller.getAttrForInt("login_user_id");
        Record rdu = controller.getAttr("login_user_record");
        
        // 获取家长信息
        Record rdp = aiParentService.getOneByUserId(login_user_id);
		if (rdp != null) {
			
			/**
			 * 设置临时变量
			 */
			controller.setAttr("login_parent_rd", rdp);
			controller.setAttr("login_parent_id", rdp.getInt("parent_id"));
			controller.setAttr("login_class_id", rdp.getInt("class_id"));
			controller.setAttr("login_student_id", rdp.getInt("student_id"));

			// 判断是否授权
			if (is_pass && PropKit.getBoolean("wxAuthModel") && 
					UserAgentUtil.isWechat(request) && StrKit.isBlank(rdu.get("wx_openid", ""))) {
				is_pass = false;
				
				String calbackUrl="http://"+PropKit.get("domain")+"/weixin/auth";
				try {
					calbackUrl=PaymentKit.urlEncode(calbackUrl);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String url=SnsAccessTokenApi.getAuthorizeURL(PropKit.get("appId"), calbackUrl, "a"+SysAppEnum.FAMILY_APP.getId()+"u"+login_user_id,false);
				//System.err.println(url);
				controller.redirect(url);
				return is_pass;
			}
			// 判断家长信息是否完整
			if (rdp.getInt("class_id")<=0 || rdp.getInt("student_id")<=0 || rdp.getInt("kindred_id")<=0) {
				is_pass = false;
				
				/**
				 * 设置临时变量
				 */
				controller.setAttr("attr_needmore", "1");
				
				if (surl.startsWith("/front/family/parent")) {
					is_pass = true;
				}else {
					controller.redirect("/front/family/parent/myinfo");
				}
			}
		}
		return is_pass;
	}
}
